﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace DGMResourcesTool.Logic.FileUtil
{
    public class FileReaderWriterUtility
    {
        /// <summary>
        /// 使用特定编码格式读取文件.
        /// </summary>
        public static string[] ReadFile(string filePath, Encoding encoding)
        {
            string[] csvLineList = File.ReadAllLines(filePath, encoding);
            return csvLineList;
        }

        /// <summary>
        /// 写入数据到CSV文件，覆盖形式
        /// </summary>
        /// <param name="csvPath">要写入的字符串表示的CSV文件</param>
        /// <param name="lineDataList">要写入CSV文件的数据，以string[]类型List表示的行集数据</param>
        public static bool WriteToCSV(string csvPath, List<string[]> lineDataList)
        {
            try
            {
                using (FileStream fs = new FileStream(csvPath.Trim(), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        StringBuilder sbCsvStr = new StringBuilder();
                        for (int i = 0; i < lineDataList.Count; i++)//<--row
                        {
                            sbCsvStr.Clear();
                            for (int j = 0; j < lineDataList[i].Length; j++)//<--col
                            {
                                sbCsvStr.Append(string.Format("{0},", lineDataList[i][j]));
                            }
                            sw.WriteLine(sbCsvStr.ToString().Substring(0, sbCsvStr.ToString().Length - 1));
                        }
                        fs.Flush();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.StackTrace);
                return false;
            }
        }


        public static string GetFileSize(string sFileFullName)
        {
            FileInfo fiInput = new FileInfo(sFileFullName);
            double len = fiInput.Length;

            string[] sizes = { "B", "KB", "MB", "GB" };
            int order = 0;
            while (len >= 1024 && order + 1 < sizes.Length)
            {
                order++;
                len = len / 1024;
            }

            string filesize = String.Format("{0:0.##} {1}", len, sizes[order]);
            return filesize;
        }


        public static double GetFileKBSize(string sFileFullName)
        {
            FileInfo fiInput = new FileInfo(sFileFullName);
            double len = fiInput.Length;
            len = len / 1024;
            return len;
        }
    }
}